import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-04-13
 * Time: 13:07
 *
 * @author 666
 */
public class TcpEcoThreadServer {
    ServerSocket serverSocket = null;

    public TcpEcoThreadServer(int port) throws IOException {
        this.serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("服务器启动");
        while (true) {
            Socket socket = serverSocket.accept();
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processServer(socket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });


        }

    }

    private void processServer(Socket socket) throws IOException {
        System.out.println("客户端上线");
        try (OutputStream outputStream = socket.getOutputStream();
             InputStream inputStream = socket.getInputStream()) {
            PrintWriter printWriter = new PrintWriter(outputStream);
            Scanner scannerSocket = new Scanner(inputStream);
            while (true) {
                if (!scannerSocket.hasNext()) {
                    System.out.println("客户端下线");
                    break;
                }
                String request = scannerSocket.next();
                String response = process(request);
                printWriter.println(response);
                printWriter.flush();
                System.out.println("请求为" + request + "响应为" + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            socket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEcoThreadServer tcpEcoThreadServer = new TcpEcoThreadServer(9000);
        tcpEcoThreadServer.start();
    }
}
